﻿using System.Collections.Generic;
using UnityEngine;

public class Tower : MonoBehaviour
{
    private Transform head;//头部
    private Transform firePoint;//开火点
    public State state;
    public float atkRang = 6;//攻击范围
    private Transform target;//攻击目标
    private float nextTime = 0;//下次发射子弹的时间
    public float interval = 1;
    private GameObject bulletPrefab;

    private void Start()
    {
        bulletPrefab = Resources.Load<GameObject>("Bullet");
        head = transform.Find("Head");
        firePoint = head.Find("FirePoint");
        state = State.idle;
    }

    private void Update()
    {
        switch (state)
        {
            case State.idle:
                StateIdel();
                break;

            case State.attack:
                StateAttack();
                break;
        }
    }

    //闲置状态  找敌人,找到了切换到攻击状态
    private void StateIdel()
    {
        //遍历敌人列表,找一个在范围内的
        var monsterList = EnemyCreater.instance.monsterList;
        for (int i = 0; i < monsterList.Count; i++)
        {
            if (InRange(monsterList[i]))
            {
                target = monsterList[i];//设置目标
                state = State.attack;
                nextTime = Time.time;//重置下次发射子弹的时间
                return;
            }
        }
    }

    private bool InRange(Transform other)
    {
        return (other.position - transform.position).sqrMagnitude < atkRang * atkRang;
    }

    //攻击状态  向敌人发射子弹,   1.敌人死亡回闲置2敌人走远了回到闲置
    private void StateAttack()
    {
        if (target == null)
        {
            state = State.idle;
            return;
        }

        if (!InRange(target))
        {
            state = State.idle;
            return;
        }

        head.LookAt(target);
        if (Time.time > nextTime)
        {
            GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
            bullet.GetComponent<Bullet>().target = target;
            nextTime += interval;
        }
    }

    //防御塔的两种状态
    public enum State
    {
        idle,
        attack,
    }
}